package com.jiawa.train.business.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.jiawa.train.business.constant.TrainConstant;
import com.jiawa.train.business.req.DailyTrainTicketQueryReq;
import com.jiawa.train.business.resp.DailyTrainTicketQueryResp;
import com.jiawa.train.business.service.DailyTrainTicketService;
import com.jiawa.train.common.resp.CommonResp;
import com.jiawa.train.common.resp.PageResp;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * @author zzl
 * @version 1.0
 */
@RestController
@RequestMapping("/daily-train-ticket")
public class DailyTrainTicketController {
    @Resource
    private DailyTrainTicketService dailyTrainTicketService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @GetMapping("/query-list")
    public CommonResp<PageResp<DailyTrainTicketQueryResp>> queryList(@Valid DailyTrainTicketQueryReq req) {

        String key = TrainConstant.trainTicketPrefix + ":" + DateUtil.formatDate(req.getDate()) + "-" + req.getStart() + "-" + req.getEnd();
        Object value = redisTemplate.opsForValue().get(key);
        if(ObjectUtil.isNull(value)) {
            PageResp<DailyTrainTicketQueryResp> pageResp = dailyTrainTicketService.queryList(req);
            redisTemplate.opsForValue().set(key, pageResp);
            return new CommonResp<>(pageResp);
        } else {
            PageResp<DailyTrainTicketQueryResp> pageResp = (PageResp<DailyTrainTicketQueryResp>) value;
            return new CommonResp<>(pageResp);
        }
    }
}
